﻿#include "tcpmonitor.h"
#include <QDebug>
#include <QElapsedTimer>

#include "iputils.h"

TCPMonitor::TCPMonitor(QObject *parent) : QThread(parent)
{

}

bool TCPMonitor::Add(BaseCommunication *comm)
{
    _communicationList.append(comm);
    return true;
}

void TCPMonitor::run()
{
    //这样设计的目的是为了在程序结束时减少等待时间,减少检查_isRunning标志的时间
    QElapsedTimer ela;
    ela.start();
    while(_isRunning)
    {
        //每60秒检查一次连通性
        QThread::msleep(100);
        if(ela.elapsed()>60*1000)
        {
            for(auto comm:_communicationList)
            {
                if(!IPUtils::IsPortListening(comm->GetCommunicationParam()))
                {
                    qCritical()<<comm->Name()<<" "<<comm->GetCommunicationParam()<<"is close";
                }
            }
            ela.restart();
        }
    }
}

void TCPMonitor::WaitForEnd()
{
    _isRunning=false;
    wait();
}
